package net.moonbiter.ebs.protocols.httpparams.tree.interp.types;

import net.moonbiter.ebs.NodeName;
import net.moonbiter.ebs.protocols.httpparams.tree.Leaf;
import net.moonbiter.ebs.protocols.httpparams.tree.Node;
import net.moonbiter.ebs.protocols.httpparams.tree.StringLeaf;
import net.moonbiter.ebs.protocols.httpparams.tree.Tree;
import net.moonbiter.ebs.validation.UnexistingParamValidationException;
import net.moonbiter.ebs.validation.ValidationException;
import net.moonbiter.ebs.validation.ValidationParamException;

import org.apache.log4j.Logger;

abstract class TreeTypeInterpreterBase {
	
	private final static Logger logger = Logger.getLogger(TreeTypeInterpreterBase.class);
	
	protected Leaf requireLeafExistence(Tree tree,
			NodeName[] namePortions) throws ValidationException{
		requireExistence(tree, namePortions);			
		if (!tree.getNode(namePortions).isLeaf()){
			throw new ValidationParamException(namePortions,"is not a simple parameter but a complex one");
		}
		return (Leaf)tree.getNode(namePortions);
	}
	
	protected Tree requireBranchExistence(Tree tree,
			NodeName[] namePortions) throws ValidationException{
		requireExistence(tree, namePortions);				
		if (tree.getNode(namePortions).isLeaf()){
			throw new ValidationParamException(namePortions,"is not a complex parameter but a simple one");
		}
		return (Tree)tree.getNode(namePortions);
	}	
	
	protected Node requireExistence(Tree tree,
			NodeName[] namePortions) throws ValidationException{
		if (!tree.hasNode(namePortions)){
			throw new UnexistingParamValidationException(namePortions);
		}
		return tree.getNode(namePortions);
	}
	
	protected String[] requireStringLeafExistence(Tree tree,
			NodeName[] namePortions) throws ValidationException{
		Object leaf = requireLeafExistence(tree, namePortions);
		if (!(leaf instanceof StringLeaf)){
			throw new ValidationParamException(namePortions,"dosn't indicate a String array");
		}
		return ((StringLeaf)leaf).getStringArray();
	}
	
	protected String requireSingleStringLeafExistence(Tree tree,
			NodeName[] namePortions) throws ValidationException{
		String[] sa = requireStringLeafExistence(tree, namePortions);
		if (sa.length!=1){
			throw new ValidationParamException(namePortions,"indicate more than one String, just one allowed in this case");
		}
		return sa[0];
	}
}
